package shop.entity;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.flown.shop.DirectoryInformation;
import org.flown.shop.entity.BaseEntity;
import org.flown.shop.entity.error.ReadError;
import org.flown.shop.entity.error.SaveError;
import org.hibernate.validator.constraints.Range;

import javax.imageio.stream.FileImageOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;


@EqualsAndHashCode(callSuper = true)
@Data
public class GoodsComment extends BaseEntity
{


    public enum Type
    {
        NORMAL,
        ADDITIONAL
    }


    @NotNull @Min(1)
    private int goodsID;
    @NotNull @Min(1)
    private int userID;
    @NotNull @Min(1)
    private int storeID;
    @NotNull @Min(1)
    private int ordersID;
    @NotNull @Range(min = 1, max = 5)
    private int detailStar = 5;//描述star
    @NotNull @Range(min = 1, max = 5)
    private int logisticsStar = 5;//物流star
    @NotNull @Range(min = 1, max = 5)
    private int attitudeStar = 5;//态度star
    private Type type = Type.NORMAL;
    private java.util.Date time = new java.util.Date();

    private String content = "[系统默认好评]";//用时转json
    private String[] base64Picture = null;


    /**
     * 默认评价
     * */
    public GoodsComment(int goods_id, int user_id, int store_id, int orders_id)
    {
        this.goodsID = goods_id;
        this.userID = user_id;
        this.storeID = store_id;
        this.ordersID = orders_id;
    }
    public GoodsComment(int goods_id, int user_id, int store_id, int orders_id,
                   int detail_star, int logistics_star, int attitude_star,
                        Type type, String content)
    {
        this.goodsID = goods_id;
        this.userID = user_id;
        this.storeID = store_id;
        this.ordersID = orders_id;
        this.detailStar = detail_star;
        this.logisticsStar = logistics_star;
        this.attitudeStar = attitude_star;
        this.type = type;
        this.content = content;
    }


    public String getDirectoryRealPath()
    {
        return DirectoryInformation.GOODS.getRealPath() + "/" + this.storeID + "/" + this.goodsID + "/comment";
    }
    public String getPictureRealPath(String name, String format) {return this.getDirectoryRealPath() + "/" + name + "." + format;}


    public boolean savePictures()
            throws IOException, SaveError
    {
        if (this.base64Picture == null)
            return false;

        //创建文件夹
        File directory = new File(this.getDirectoryRealPath());
        if (!directory.exists())
            directory.mkdir();

        ObjectMapper mapper = new ObjectMapper();
        ArrayNode root = (ArrayNode) mapper.readTree(this.content);
        if (root.size() - 1 != this.base64Picture.length)
            throw new SaveError("content.size - 1 > base64Picture.length");
        for (int i = 0; i < this.base64Picture.length; i++)
        {
            ObjectNode node = (ObjectNode)root.get(i + 1);
            if (node == null)
                break;
            String base64_pic = this.base64Picture[i];
            byte[] bytes = Base64.getDecoder().decode(base64_pic);
            File file = new File(this.getPictureRealPath(node.get("name").toString(), node.get("format").toString()));
            if (!file.exists())
                file.createNewFile();
            FileImageOutputStream output = new FileImageOutputStream(file);
            output.write(bytes);
            output.close();
        }
        return true;
    }



    /**
     * @param index 从1开始
     * */
    public String getPictureFormat(int index)
            throws JsonProcessingException, ReadError
    {
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode root = (ArrayNode)mapper.readTree(this.content);
        JsonNode node = root.get(index);
        if (!node.isObject())
            throw new ReadError("error index");
        return node.get("format").toString();
    }
    public String getPictureFormatByName(String name)
            throws IOException
    {
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode root = (ArrayNode)mapper.readTree(this.content);
        int count = root.size() - 1;
        for(int i = 0; i < count; i++)
        {
            JsonNode node = root.get(i + 1);
            if (!node.isObject())//不是对象，则不是图片
                continue;
            if (node.get("name").toString().equals(name))
            {
                return node.get("format").toString();
            }
        }
        return null;
    }
    /**
     * @param index 从1开始
     * */
    public byte[] getPicture(int index)
            throws IOException, ReadError
    {
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode root = (ArrayNode)mapper.readTree(this.content);
        int count = root.size() - 1;
        if (index == 0 || index > count)
            throw new ReadError("object not exists");
        JsonNode node = root.get(index);
        if (!node.isObject())//不是对象，则不是图片
            throw new ReadError("isn't object");
        File file = new File(this.getPictureRealPath(node.get("name").toString(), node.get("format").toString()));
        if (!file.exists())
            throw new ReadError("file isn't exists");
        FileInputStream input = new FileInputStream(file);
        return input.readAllBytes();
    }
    public byte[] getPictureByName(String name)
            throws IOException, ReadError
    {
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode root = (ArrayNode)mapper.readTree(this.content);
        int count = root.size() - 1;
        for(int i = 0; i < count; i++)
        {
            JsonNode node = root.get(i + 1);
            if (node == null)
                continue;
            if (!node.isObject())
                continue;
            if (node.get("name").toString().equals(name))
            {
                File file = new File(this.getPictureRealPath(node.get("name").toString(), node.get("format").toString()));
                if (!file.exists())
                    throw new ReadError("file isn't exists");
                FileInputStream input = new FileInputStream(file);
                return input.readAllBytes();
            }
        }
        return null;
    }
    public byte[][] getPictures()
            throws IOException, ReadError
    {
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode root = (ArrayNode)mapper.readTree(this.content);
        int count = root.size() - 1;
        byte[][] bytes = new byte[count][];
        for (int i = 0; i < count; i++)
        {
            JsonNode node = root.get(i + 1);
            if (node == null)
                throw new ReadError("node == null");
            if (!node.isObject())//不是对象则下一个
                continue;
            File file = new File(this.getPictureRealPath(node.get("name").toString(), node.get("format").toString()));
            if (!file.exists())
                throw new ReadError("file isn't exists");
            FileInputStream input = new FileInputStream(file);
            bytes[i] = input.readAllBytes();
        }
        return bytes;
    }
}



